package com.x.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.x.utils.StringUtil;

/**
 * <p>
 * Description:
 * </p>
 * 
 * @Author Chenkangming
 * @Date 2015年11月9日
 * @version 1.0
 */
public class HttpUtil {
	private static Logger log = LoggerFactory.getLogger("HttpUtil");
	
	public static Map<String,String> getParamToMap(HttpServletRequest request){
		Map<String, String> paramsMap = new HashMap<String, String>();
		Set<String> rquestParams = request.getParameterMap().keySet();
		for (String paramsKey : rquestParams) {
			paramsMap.put(paramsKey, request.getParameter(paramsKey));
		}
		return paramsMap;
	}

	/**
	 * 
	 * 获取POST上来的参数
	 * 
	 * 
	 * 
	 * @param request
	 * 
	 * @return
	 * 
	 */
	public static JSONObject getJsonParams(HttpServletRequest request) {
		JSONObject params = new JSONObject();
		BufferedReader reader = null;
		StringBuffer buffer = new StringBuffer();
		try {
			reader = request.getReader();
			String string = "";
			while ((string = reader.readLine()) != null) {
				buffer.append(string);
			}
			log.info(buffer.toString());
		} catch (Exception e) {
			log.error("{}", e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					log.error("{}", e);
				}
			}
		}
		if (StringUtil.isNotEmpty(buffer.toString())) {
			try {
				params = JSONObject.parseObject(buffer.toString());
			} catch (Exception e) {
				log.error("{}", e);
			}
		}
		return params;
	}

	/**
	 * 
	 * URLEncoder
	 * 
	 * 
	 * 
	 * @param obj
	 * 
	 * @return
	 * 
	 */
	public static String UrlEncoder(String obj) {
		if (StringUtil.isEmpty(obj)) {
			return obj;
		}
		try {
			obj = URLEncoder.encode(obj, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("{}", e);
		}
		return obj;
	}

	/**
	 * 
	 * URLDncoder
	 * 
	 * 
	 * 
	 * @param obj
	 * 
	 * @return
	 * 
	 */
	public static String UrlDncoder(String obj) {
		if (StringUtil.isEmpty(obj)) {
			return obj;
		}
		try {
			obj = URLDecoder.decode(obj, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("{}", e);
		}
		return obj;
	}
	
	public static void main(String[] args) {
		System.out.println(UrlEncoder("TOKEN_m0+RlYBVv7NDa9jMsMgnEp9D9iztJ5bj8pAvfNzrNdWE+TgqVl5btQ=="));
	}
}
